//
//  TwoTestVC.m
//  WebViewJSBridgeDemo
//
//  Created by Tianlong on 2019/9/7.
//  Copyright © 2019 叶建华. All rights reserved.
//

#import "TwoTestVC.h"
#import "JSBridge_JS.h"

@interface TwoTestVC ()<UIWebViewDelegate>
@property (strong, nonatomic) UIWebView *webView;

@end

@implementation TwoTestVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    self.webView.delegate = self;
    [self.view addSubview:self.webView];
    
    NSString *indexPath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];
    NSString *appHtml = [NSString stringWithContentsOfFile:indexPath encoding:NSUTF8StringEncoding error:nil];
    NSURL *baseUrl = [NSURL fileURLWithPath:indexPath];
    [self.webView loadHTMLString:appHtml baseURL:baseUrl];
    
    /** 方法解释
     [self.bridge registerHandler:@"openCamera" handler:^(id data, WVJBResponseCallback responseCallback) {
     NSLog(@"需要%@图片", data[@"count"]);
     
     UIImagePickerController *imageVC = [[UIImagePickerController alloc] init];
     imageVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
     [self presentViewController:imageVC animated:YES completion:nil];
     }];
     
     registerHandler: 将方法名存在本地messageHandlers中，
     handler回调通过：flushMessageQueue 方法中进行处理
     */
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSURL *url = request.URL;
    NSLog(@"url.host === %@",url.host);
    if ([request.URL.host isEqualToString:@"__bridge_prepare__"]) {//预处理：注册本地js代码，创建桥接
        NSString *prepareJS = WebBridge_JS();
        [self.webView stringByEvaluatingJavaScriptFromString:prepareJS];
    }
    else if ([request.URL.host isEqualToString:@"__bridge_message__"]) {//交互：消息处理
        //调用原生方法
        NSString *jsSendMessage = [self.webView stringByEvaluatingJavaScriptFromString:@"WebViewJavascriptBridge._fetchQueue()"];
        NSLog(@"jsSendMessage = %@",jsSendMessage);
        //收到message后交由Birdge进行处理
        //1、通过regiset方法注册
        //2、通过 flushMessageQueue:(NSString *)messageQueueString 方法处理message，
        //3、回掉JS，bridge（Native）对象，调用 callhandler方法（具体查看内部实现），参考_dispatchMessage:(WVJBMessage*)message
    }
    
    return YES;
}


@end
